const exec = require('child_process').exec;
const execSync = require('child_process').execSync;
const Dayjs = require('dayjs');
const relativeTime = require('dayjs/plugin/relativeTime');

// dayjs 格式处理
require('dayjs/locale/zh-cn');

Dayjs.locale('zh-cn');
Dayjs.extend(relativeTime);
const replaceDate = (message) => message.replace(/#DATE<([^>]+)>/gi, (_, p1) => new Dayjs(p1).fromNow());

// 删除空行
const removeEmptyLines = (string) => {
  return string.replace(/[\s\r\n]+$/, '');
};

const command = (command, callback) => {
  const gitCommand = ['git', command].join(' ');
  if (callback) {
    exec(gitCommand, function (err, stdout) {
      if (err) {
        return callback(err);
      }
      callback(null, removeEmptyLines(stdout));
    });
  } else {
    return removeEmptyLines(String(execSync(gitCommand)));
  }
};

const getCommitMessages = () =>
  replaceDate(
    execSync(
      // 和git-commit 关键字串联起来，也可删除
      `git log --no-merges -n 1 --grep="^[feat|fix|perf|refactor|revert|style|test]" --format=format:"* %s (@%cn #DATE<%cd>)"`,
      '',
    )
      .toString()
      .trim(),
  );

// 检查仓库是否不存在未提交的更改
const checkRepoIsClear = () =>
  execSync('git status -suno')
    .toString()
    .trim()
    .replace(/[\r\n]+$/, '').length === 0;

const branch = command('rev-parse --abbrev-ref HEAD');
const commitHash = command('rev-parse HEAD');
const commitMessages = getCommitMessages();
const repoIsEmpty = checkRepoIsClear();

module.exports = {
  branch,
  commitHash,
  commitMessages,
  repoIsEmpty,
};
